import AudioList from "@/utils/audio-list/main";
import { onKeyPressed } from "@vueuse/core";
import { onUnmounted, onActivated, onDeactivated, onMounted } from "vue";
const audio = AudioList.create();
const keyconfig = [
  {
    label: "播放/暂停,",
    key: [" "],
    des: "空格键",
    handler: () => {
      audio.paused ? audio.play() : audio.pause();
    },
  },
  {
    label: "上一首/下一首",
    key: ["ArrowRight", "ArrowLeft", "A", "a", "D", "d"],
    des: "向左向右键头",
    handler: (event: any) => {
      switch (event.key) {
        case "ArrowRight":
        case "D":
        case "d":
          audio.next();
          break;
        case "ArrowLeft":
        case "a":
        case "A":
          audio.prev();
          break;
      }
    },
  },
];
export default function useAudioShortKey() {
  let clearLenters: any[] = [];
  onMounted(() => {
    init();
    console.log("audio key bind onMounted");
  });
  onActivated(() => {
    init();

    console.log("audio key bind onActivated");
  });

  onDeactivated(() => {
    clears();
    console.log("audio key onunbind onDeactivated");
  });
  onUnmounted(() => {
    clears();
    console.log("audio key onunbind onUnmounted");
  });

  function clears() {
    clearLenters.forEach((clear) => {
      clear();
    });
    clearLenters = [];
  }

  function init() {
    if (clearLenters.length > 0) {
      clears();
    }
    clearLenters = keyconfig.map((keyConfig) => {
      return onKeyPressed(keyConfig.key, keyConfig.handler, { dedupe: true });
    });
  }
}
